<template>
	<el-container class="chat-page">
		<el-aside width="280px" class="chat-list-box">
			<div class="chat-list-header">
				<el-input class="search-text" placeholder="搜索" v-model="searchText">
					<i class="el-icon-search el-input__icon" slot="prefix"> </i>
				</el-input>
			</div>
			<div class="chat-list-loading"  v-if="loading" v-loading="true" element-loading-text="消息接收中..."
				element-loading-spinner="el-icon-loading" element-loading-background="#eee">
				<div class="chat-loading-box"></div>
			</div>
			<el-scrollbar class="chat-list-items">
				<div v-for="(chat,index) in chatStore.chats" :key="index"  @dblclick="onWind(chat)">
					<chat-item v-show="!chat.delete && chat.showName && chat.showName.includes(searchText)" :chat="chat" :index="index"
						@click.native="onActiveItem(chat)" @delete="onDelItem(index)" @wind="onWind(chat)"  @top="onTop(index)"
						:active="chat === chatStore.activeChat"></chat-item>
				</div>
			</el-scrollbar>
		</el-aside>
		<el-container class="chat-box">
			<chat-box v-if="chatStore.activeChat && isChatShow" 
				:chat="chatStore.activeChat" 
				:flag="true" 
				:key="chatStore.activeChat.targetId">
			</chat-box>
			<div v-else-if="chatStore.activeChat && !isChatShow" class="chat-windowed-tip">
				<i class="el-icon-message"></i>
				<p>会话已在独立窗口打开</p>
			</div>
		</el-container>
	</el-container>
</template>

<script>
	import ChatItem from "../components/chat/ChatItem.vue";
	import ChatBox from "../components/chat/ChatBox.vue";
	export default {
		name: "chat",
		components: {
			ChatItem,
			ChatBox
		},
		data() {
			return {
				searchText: "",
				messageContent: "",
				group: {},
				groupMembers: [],
				isChatShow: true
			}
		},
		methods: {
			// 检查窗口状态时添加防护
			checkWindowStatus(chatId) {
				try {
					const windowedChats = JSON.parse(localStorage.getItem('windowedChats') || '[]');
					return Array.isArray(windowedChats) && windowedChats.includes(chatId);
				} catch (e) {
					console.error('检查窗口状态失败:', e);
					return false;
				}
			},

			// 添加独立窗口记录时添加防护
			addWindowStatus(chatId) {
				try {
					const windowedChats = JSON.parse(localStorage.getItem('windowedChats') || '[]');
					if (Array.isArray(windowedChats) && !windowedChats.includes(chatId)) {
						windowedChats.push(chatId);
						localStorage.setItem('windowedChats', JSON.stringify(windowedChats));
					}
				} catch (e) {
					console.error('添加窗口状态失败:', e);
				}
			},

			// 移除独立窗口记录时添加防护
			removeWindowStatus(chatId) {
				try {
					const windowedChats = JSON.parse(localStorage.getItem('windowedChats') || '[]');
					if (Array.isArray(windowedChats)) {
						const index = windowedChats.indexOf(chatId);
						if (index > -1) {
							windowedChats.splice(index, 1);
							localStorage.setItem('windowedChats', JSON.stringify(windowedChats));
						}
					}
				} catch (e) {
					console.error('移除窗口状态失败:', e);
				}
			},

			onActiveItem(chat) {
				if (!chat) return;
				
				// 检查是否已经窗口化
				if (this.checkWindowStatus(chat.targetId)) {
					// 使用 nextTick 确保 DOM 更新完成
					this.$nextTick(() => {
						this.isChatShow = false;
						this.$store.commit("getactiveChat", chat.targetId);
					});
				} else {
					// 使用 nextTick 确保 DOM 更新完成
					this.$nextTick(() => {
						this.isChatShow = true;
						this.$store.commit("getactiveChat", chat.targetId);
					});
				}
			},
			onDelItem(index) {
				this.$store.commit("removeChat", index);
			},
			onTop(chatIdx) {
				this.$store.commit("moveTop", chatIdx);
			},
			onWind(chat) {
				this.$nextTick(() => {
					this.$store.commit("getactiveChat", chat.targetId);
					this.isChatShow = false;
					
					// 记录窗口化状态
					this.addWindowStatus(chat.targetId);

					// 使用新窗口打开
					const params = {
						index: chat.targetId,
					}
					const url = `${window.location.origin}/#/home/chatbox/${JSON.stringify(params)}`;
					const newWindow = window.open(url, '_blank', 'width=740,height=975');
					
					// 监听新窗口关闭事件
					if (newWindow) {
						const checkWindow = setInterval(() => {
							if (newWindow.closed) {
								clearInterval(checkWindow);
								this.removeWindowStatus(chat.targetId);
								if (this.chatStore.activeChat && this.chatStore.activeChat.targetId === chat.targetId) {
									this.isChatShow = true;
								}
							}
						}, 500);
					}
				});
			},
			// 添加窗口关闭处理方法
			handleWindowClose() {
				// 清空本地存储中的窗口状态
				localStorage.removeItem('windowedChats');
			}
		},
		computed: {
			chatStore() {
				return this.$store.state.chatStore;
			},
			loading(){
				return this.chatStore.loadingGroupMsg || this.chatStore.loadingPrivateMsg
			}
		},
		watch: {
			// 监听活动聊天的变化
			'chatStore.activeChat': {
				handler(newChat) {
					if (newChat) {
						// 使用 nextTick 确保 DOM 更新完成
						this.$nextTick(() => {
							this.isChatShow = !this.checkWindowStatus(newChat.targetId);
						});
					}
				},
				immediate: true
			}
		},
		created() {
			// 改用 window 事件监听
			window.addEventListener('message', (event) => {
				if (event?.data?.type === 'chat-window-closed') {
					this.removeWindowStatus(event.data.chatId);
					if (this.chatStore?.activeChat && this.chatStore.activeChat.targetId === event.data.chatId) {
						this.isChatShow = true;
					}
				}
			});

			// 初始化时清理可能存在的脏数据
			this.handleWindowClose();
		},
		beforeDestroy() {
			// 修复事件监听器移除方法
			window.removeEventListener('message', (event) => {
				if (event?.data?.type === 'chat-window-closed') {
					this.removeWindowStatus(event.data.chatId);
					if (this.chatStore?.activeChat && this.chatStore.activeChat.targetId === event.data.chatId) {
						this.isChatShow = true;
					}
				}
			});
		}
	}
</script>

<style lang="scss">
	.chat-page {
		.chat-list-box {
			display: flex;
			flex-direction: column;
			border-right: #53a0e79c solid 1px;	
			background: white;
			width: 3rem;

			.chat-list-header {
				padding: 3px 8px;
				line-height: 50px;
				border-bottom: 1px #ddd solid;
				
				.el-input__inner {
					border-radius: 10px !important;
					background-color: #F8F8F8;
				}
				
			}
			
			.chat-list-loading{
				height: 50px;
				background-color: #eee;
				
				.chat-loading-box{
					height: 100%;
				}
			}
			
			.chat-list-items {
				flex: 1;
				background: #F8F8F8;
				margin: 0 3px;
			}
		}
		.chat-box {
			.chat-windowed-tip {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				height: 100%;
				color: #909399;
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				text-align: center;
				width: 100%;
				
				i {
					font-size: 48px;
					margin-bottom: 16px;
					color: #53a0e7;
				}
				
				p {
					font-size: 16px;
					margin: 0;
					color: #606266;
					font-weight: 500;
				}
			}
		}
	}
</style>